package com.waikuai.shop.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.waikuai.shop.service.CaptchaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.concurrent.TimeUnit;

/**
 * 验证码服务实现类
 * @author waikuai
 */
@Slf4j
@Service
public class CaptchaServiceImpl implements CaptchaService {

    private final StringRedisTemplate redisTemplate;

    /**
     * 验证码过期时间（分钟）
     */
    @Value("${captcha.expiration:5}")
    private Long captchaExpiration;

    /**
     * 验证码长度
     */
    @Value("${captcha.length:4}")
    private Integer captchaLength;

    /**
     * 验证码宽度
     */
    @Value("${captcha.width:120}")
    private Integer captchaWidth;

    /**
     * 验证码高度
     */
    @Value("${captcha.height:40}")
    private Integer captchaHeight;

    /**
     * 验证码缓存前缀
     */
    private static final String CAPTCHA_PREFIX = "captcha:";

    public CaptchaServiceImpl(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public BufferedImage generateCaptcha(String key) {
        if (StrUtil.isBlank(key)) {
            key = IdUtil.simpleUUID();
        }

        // 生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaWidth, captchaHeight, captchaLength, 50);
        String code = lineCaptcha.getCode();
        BufferedImage image = lineCaptcha.getImage();

        // 缓存验证码
        String cacheKey = CAPTCHA_PREFIX + key;
        redisTemplate.opsForValue().set(cacheKey, code, captchaExpiration, TimeUnit.MINUTES);

        log.debug("生成验证码: key={}, code={}", key, code);
        return image;
    }

    @Override
    public boolean validateCaptcha(String key, String code) {
        if (StrUtil.isBlank(key) || StrUtil.isBlank(code)) {
            return false;
        }

        String cacheKey = CAPTCHA_PREFIX + key;
        String cachedCode = redisTemplate.opsForValue().get(cacheKey);

        if (StrUtil.isBlank(cachedCode)) {
            log.debug("验证码不存在或已过期: key={}", key);
            return false;
        }

        // 验证码不区分大小写
        boolean isValid = code.equalsIgnoreCase(cachedCode);

        // 验证后删除验证码
        redisTemplate.delete(cacheKey);

        log.debug("验证验证码: key={}, input={}, cached={}, result={}",
                key, code, cachedCode, isValid);

        return isValid;
    }

    @Override
    public String generateCaptchaText() {
        return CaptchaUtil.createLineCaptcha(captchaWidth, captchaHeight, captchaLength, 50).getCode();
    }
}